package com.iteaj.iot.server.dtu;

import com.iteaj.iot.CoreConst;
import com.iteaj.iot.message.DefaultMessageHead;
import com.iteaj.iot.server.ServerMessage;
import com.iteaj.iot.server.dtu.message.DtuMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;

/**
 * dtu 上电第一包设备编号解码器
 * 此handler要求dtu上报的第一包必须是设备编号
 */
public class DtuFirstDeviceSnPackageHandler extends ChannelInboundHandlerAdapter {

    private DtuMessageDecoder messageDecoder;

    public DtuFirstDeviceSnPackageHandler(DtuMessageDecoder messageDecoder) {
        this.messageDecoder = messageDecoder;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Attribute attr = ctx.channel().attr(CoreConst.EQUIP_CODE);
        if(attr.get() == null) { // 设备编号不存在说明是DTU第一次上报设备编号
            ByteBuf buf = (ByteBuf) msg;
            if(buf.readableBytes() > 0) {
                byte[] message = new byte[buf.readableBytes()];
                buf.readBytes(message);
                String deviceSn = new String(message);

                // 由于第一包是字符串类型的设备编号 不执行读构建{@link SocketMessage#readBuild()}
                ServerMessage dtuMessage = messageDecoder.createMessage(message);

                // 设置设备编号
                ((DtuMessage) dtuMessage).setEquipCode(deviceSn);

                // 设置DTU报文头
                dtuMessage.setHead(((DtuMessage) dtuMessage).buildFirstHead());

                // 交由下一个handler
                super.channelRead(ctx, dtuMessage);
            } else {
                super.channelRead(ctx, msg);
            }
        } else {
            super.channelRead(ctx, msg);
        }
    }

}
